package config

import (
	"github.com/go-sql-driver/mysql"
	"go-admin-official/modules/logger"
	"gopkg.in/yaml.v2"
	"io/ioutil"
)

type Config struct {
	Debug              bool          `json:"debug" yaml:"debug"`
	Frontend           Frontend      `json:"frontend" yaml:"frontend"`
	Logger             logger.Config `json:"logger" yaml:"logger"`
	Port               string        `json:"port" yaml:"port"`
	Database           Database      `json:"database" yaml:"database"`
	AppSecret          string        `json:"app_secret" yaml:"app_secret"`
	DiscussSecret      string        `json:"discuss_secret" yaml:"discuss_secret"`
	AliPayAppID        string        `json:"alipay_app_id" yaml:"alipay_app_id"`
	AliPayPrivateKey   string        `json:"alipay_private_key" yaml:"alipay_private_key"`
	AliPayPublicKey    string        `json:"alipay_public_key" yaml:"alipay_public_key"`
	WxPayAppID         string        `json:"wx_pay_app_id" yaml:"wx_pay_app_id"`
	WxPayAppSecret     string        `json:"wx_pay_app_secret" yaml:"wx_pay_app_secret"`
	WxPayKey           string        `json:"wx_pay_key" yaml:"wx_pay_key"`
	WxPayMchID         string        `json:"wx_pay_mch_id" yaml:"wx_pay_mch_id"`
	UpyunSecurityToken string        `json:"upyun_security_token" yaml:"upyun_security_token"`
	TokenSessionTime   int64         `json:"token_session_time" yaml:"token_session_time"`
}

type Database struct {
	User         string            `json:"user" yaml:"user"`
	Passwd       string            `json:"passwd" yaml:"passwd"`
	Net          string            `json:"net" yaml:"net"`
	Addr         string            `json:"addr" yaml:"addr"`
	DBName       string            `json:"db_name" yaml:"db_name"`
	Params       map[string]string `json:"params" yaml:"params"`
	Collation    string            `json:"collation" yaml:"collation"`
	MaxIdleConns int               `json:"max_idle_conns" yaml:"max_idle_conns"`
	MaxOpenConns int               `json:"max_open_conns" yaml:"max_open_conns"`
}

func (d Database) Dsn() string {
	var c = mysql.Config{
		User:                 d.User,
		Passwd:               d.Passwd,
		Net:                  d.Net,
		Addr:                 d.Addr,
		DBName:               d.DBName,
		Params:               d.Params,
		Collation:            d.Collation,
		AllowNativePasswords: true,
	}
	return c.FormatDSN()
}

type Frontend struct {
	PagePath   string `json:"page_path" yaml:"page_path"`
	AssetsPath string `json:"assets_path" yaml:"assets_path"`
}

var _c = new(Config)

func Get() *Config {
	return _c
}

func InitFromYaml(path string) error {
	content, err := ioutil.ReadFile(path)
	if err != nil {
		return err
	}
	err = yaml.Unmarshal(content, _c)
	if err != nil {
		return err
	}
	return nil
}
